# -*- coding: UTF-8 -*-
# @file:crawl.py
# @time:2021/03/18
import requests
from urllib import parse
import os
from uuid import uuid4




headers = {
    'Cookie': 'BIDUPSID=EA67B328F35F7F59FC6D9C4DC9F87BCE; PSTM=1605157653; BAIDUID=EA67B328F35F7F59FD02FE21DC8C52DA:FG=1; BDUSS=5ReUxNTjNnNXkyZFNrcG1qSzdSeEVwT0syMHcwb3lEbjFONm1BMUpxaEhKLTlmRVFBQUFBJCQAAAAAAAAAAAEAAAC8H3giVmFnYWx1bmEwOTE2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEeax19HmsdfUn; BDUSS_BFESS=5ReUxNTjNnNXkyZFNrcG1qSzdSeEVwT0syMHcwb3lEbjFONm1BMUpxaEhKLTlmRVFBQUFBJCQAAAAAAAAAAAEAAAC8H3giVmFnYWx1bmEwOTE2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEeax19HmsdfUn; MCITY=-%3A; indexPageSugList=%5B%22%E6%88%AA%E5%B1%8F%E8%BD%AF%E4%BB%B6%22%2C%22%E9%9B%A8%E6%9E%9C%22%2C%22%E6%97%A5%E5%BC%8F%20%E8%8C%B6%E5%AE%A4%22%2C%22%E6%97%A5%E5%BC%8F%E8%80%81%E5%BC%8F%E5%AE%A4%E5%86%85%22%2C%22%E6%97%A5%E5%BC%8F%E5%B0%8F%E5%B1%8B%22%5D; cleanHistoryStatus=0; __yjs_duid=1_5112087a94a9fee3fada679dcbe78f261614494671710; firstShowTip=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=33513_33358_33344_31254_33594_33392_22160; BDSFRCVID=CPPOJexroG3Vmn5e_2ayJRmAd2KK0nQTDYLEHWJAh7T2grFVgHpaEG0PtDRJDf_-K4eiogKK0gOTH6KF_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCK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zYmQ5YzlhODUzZmQ2Zjg2YmI3NDQ2ZDU4Y2UyMGEwNDM5YjFiYzY0OGU1NWRkMmRlMzg2ZTIxZmFhMmZjMDY3NjY0MmZkYWNlMWIyYmE5NGQ5YzlkNWQz',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
    'Referer': 'https://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E6%9F%AF%E5%9F%BA',
    'Connection': 'keep-alive'
}

def download(url):

    # filename = 'imgs'
    filename = keyword
    if not os.path.exists(filename):
        os.makedirs(filename)

    imgs = requests.get(url,headers=headers)
    with open (filename+'/{}.jpg'.format(uuid4()),'wb') as f:
        f.write(imgs.content)



def get_link(url):
    html = requests.get(url,headers=headers)
    try:
        content=html.json()['data']
        for img in content:
            print(img['middleURL'])
            download(img['middleURL'])

    except:
        pass







keyword = input('输入搜索的图片名称：')
kw = parse.quote(keyword)
page = int(input('输入要下载多少页（每页30个）：'))

# kw = parse.quote('柯基')

for i in range(1,page):
    url='https://image.baidu.com/search/acjson?tn=resultjson_com' \
        '&logid=8918771870280311431&ipn=rj&ct=201326592&is=' \
        '&fp=result&queryWord={}&cl=2&lm=-1' \
        '&ie=utf-8&oe=utf-8&adpicid=&st=&z=&ic=&hd=&latest=' \
        '&copyright=&word={}&s=&se=&tab=&width=' \
        '&height=&face=&istype=&qc=&nc=1&fr=&expermode=' \
        '&force=&pn={}&rn=30&gsm=1e&1616059341480='.format(kw,kw,i*30)

    # print(url)
    get_link(url)
